package com.lsl.endworkvol.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.lsl.endworkvol.entity.Activity;
import com.lsl.endworkvol.entity.Leader;
import com.lsl.endworkvol.entity.SignUpNote;
import com.lsl.endworkvol.service.ActivityService;
import com.lsl.endworkvol.service.ActivitySignUpService;
import com.lsl.endworkvol.service.LeaderService;
import com.lsl.endworkvol.utils.StatusTool;

@Controller
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivitySignUpService activitySignUpService;

    @Autowired
    private LeaderService leaderService;

    @RequestMapping(path = "/admin/create_activity_page", method = RequestMethod.GET)
    public ModelAndView toCreateActivityPage(ModelAndView modelAndView) {
        modelAndView.setViewName("admin/activities_create");
        modelAndView.addObject("leaders", leaderService.getUsers());
        System.out.println("[ActivityController] +++++ Leader 列表数据：" + leaderService.getUsers().toString());
        return modelAndView;
    }

    @RequestMapping(path = "/admin/activities_list_page", method = RequestMethod.GET)
    public ModelAndView toAdminActivitiesListPage(ModelAndView modelAndView) {
        List<Activity> activitiesList = activityService.getActivities();
        List<String> leadersNameList = new ArrayList<>();
        activitiesList.forEach(activity -> {
            leadersNameList.add(((Leader)leaderService.getUser(activity.getLeaderId())).getUsername());
        });
        modelAndView.setViewName("admin/activities_list");
        modelAndView.addObject("activitiesList", activityService.getActivities());
        modelAndView.addObject("leadersNameList", leadersNameList);
        return modelAndView;
    }

    @RequestMapping(path = "/leader/activities_list_page", method = RequestMethod.GET)
    public ModelAndView toLeaderActivitiesListPage(ModelAndView modelAndView, HttpServletRequest request) {
        modelAndView.setViewName("leader/activities_list");
        modelAndView.addObject(
            "activitiesList", 
            activityService.getActivities(
                request.getSession().getAttribute("userid").toString()
            )
        );
        return modelAndView;
    }

    @RequestMapping(path = "/leader/activities_checkout_list_page", method = RequestMethod.GET)
    public ModelAndView toLeaderActivitiesCheckOutPage(ModelAndView modelAndView, HttpServletRequest request) {
        modelAndView.setViewName("leader/activities_checkout_list");
        List<Activity> activitiesList = activityService.getActivities(
            request.getSession().getAttribute("userid").toString()
        );
        List<String> userListEmpty = new ArrayList<>();
        List<String> notesCheckOutStatusListEmpty = new ArrayList<>();
        List<Integer> notesIdListEmpty = new ArrayList<>();
        modelAndView.addObject("selectedActivityId", "");
        modelAndView.addObject("activitiesList", activitiesList);
        modelAndView.addObject("userList", userListEmpty);
        modelAndView.addObject("notesCheckOutStatusList", notesCheckOutStatusListEmpty);
        modelAndView.addObject("notesIdList", notesIdListEmpty);
        return modelAndView;
    }

    @RequestMapping(path = "/leader/activities_grade_page", method = RequestMethod.GET)
    public ModelAndView toLeaderActivitiesGradePage(ModelAndView modelAndView, HttpServletRequest request) {
        modelAndView.setViewName("leader/activities_grade");
        List<Activity> AllactivitiesList = activityService.getActivities(
            request.getSession().getAttribute("userid").toString()
        );
        List<Activity> activitiesList = new ArrayList<>();
        Date dateToday = new Date();
        AllactivitiesList.forEach(activity -> {
            if (activity.getEndTime().before(dateToday)) {
                activitiesList.add(activity);
            }
        });
        List<String> userListEmpty = new ArrayList<>();
        List<String> notesCheckOutStatusListEmpty = new ArrayList<>();
        List<Integer> notesIdListEmpty = new ArrayList<>();
        List<Integer> notesGradeListEmpty = new ArrayList<>();
        modelAndView.addObject("selectedActivityId", "");
        modelAndView.addObject("activitiesList", activitiesList);
        modelAndView.addObject("userList", userListEmpty);
        modelAndView.addObject("notesCheckOutStatusList", notesCheckOutStatusListEmpty);
        modelAndView.addObject("notesIdList", notesIdListEmpty);
        modelAndView.addObject("notesGradeList", notesGradeListEmpty);
        return modelAndView;
    }

    @RequestMapping(path = "/volunteer/activities_list_page", method = RequestMethod.GET)
    public ModelAndView toVolunteerActivitiesListPage(ModelAndView modelAndView, HttpServletRequest request) {
        modelAndView.setViewName("volunteer/activities_list");
        List<Activity> activitiesList = new ArrayList<>();
        List<String> leadersNameList = new ArrayList<>();
        List<String> notesCheckOutStatusList = new ArrayList<>();
        List<Integer> notesIdList = new ArrayList<>();
        List<SignUpNote> signUpNotes = activitySignUpService.getNotes(() -> {
            SignUpNote temp = new SignUpNote();
            temp.setVolunteerId(
                Integer.parseInt((String)request.getSession().getAttribute("userid"))
            );
            return temp;
        });
        for (SignUpNote signUpNote : signUpNotes) {
            activitiesList.add(
                activityService.getActivity(String.valueOf(signUpNote.getActivityId()))   
            );
            leadersNameList.add(((Leader)leaderService.getUser(
                activityService.getActivity(
                    String.valueOf(signUpNote.getActivityId())
                ).getLeaderId()
            )).getUsername());
            notesIdList.add(signUpNote.getId());
            notesCheckOutStatusList.add(signUpNote.getCheckOutFlag() == 1 ? "已签到" : "未签到");
        }
        modelAndView.addObject("activitiesList", activitiesList);
        modelAndView.addObject("notesCheckOutStatusList", notesCheckOutStatusList);
        modelAndView.addObject("notesIdList", notesIdList);
        modelAndView.addObject("leadersNameList", leadersNameList);
        return modelAndView;
    }

    @RequestMapping(path = "/volunteer/activities_grade_list_page", method = RequestMethod.GET)
    public ModelAndView toVolunteerActivitiesGradePage(ModelAndView modelAndView, HttpServletRequest request) {
        modelAndView.setViewName("volunteer/activities_grade_list");
        List<Activity> activitiesList = new ArrayList<>();
        List<String> notesCheckOutStatusList = new ArrayList<>();
        List<Integer> notesGradeList = new ArrayList<>();
        List<SignUpNote> signUpNotes = activitySignUpService.getNotes(() -> {
            SignUpNote temp = new SignUpNote();
            temp.setVolunteerId(
                Integer.parseInt((String)request.getSession().getAttribute("userid"))
            );
            return temp;
        });
        for (SignUpNote signUpNote : signUpNotes) {
            activitiesList.add(
                activityService.getActivity(String.valueOf(signUpNote.getActivityId()))
            );
            notesCheckOutStatusList.add(signUpNote.getCheckOutFlag() == 1 ? "已签到" : "未签到");
            notesGradeList.add(signUpNote.getScore() == null ? -1 : signUpNote.getScore());
        }
        modelAndView.addObject("activitiesList", activitiesList);
        modelAndView.addObject("notesCheckOutStatusList", notesCheckOutStatusList);
        modelAndView.addObject("notesGradeList", notesGradeList);
        return modelAndView;
    }

    @GetMapping(value = "/admin/activity_edit_page/{id}")
    public ModelAndView toEditActivityPage(@PathVariable(value = "id") String id, ModelAndView modelAndView) {
        modelAndView.setViewName("admin/activities_edit");
        modelAndView.addObject("activity", activityService.getActivity(id));
        modelAndView.addObject("leaders", leaderService.getUsers());
        return modelAndView;
    }

    @RequestMapping(path = "/volunteer/activities_playground_page", method = RequestMethod.GET)
    public ModelAndView toActivityPlayGroundPage(ModelAndView modelAndView) {
        modelAndView.setViewName("volunteer/activities_playground");
        List<Activity> allActivitiesList = activityService.getActivities();
        Date dateToday = new Date();
        List<Activity> activitiesList = new ArrayList<>();
        for (Activity activity : allActivitiesList) {
            /// 如果活动已经结束，则不显示在活动广场页面
            if (!activity.getEndTime().before(dateToday)) {
                activitiesList.add(activity);
            }
        }
        modelAndView.addObject("activitiesList", activitiesList);
        return modelAndView;
    }

    @SuppressWarnings("null")
    @RequestMapping(path = "/admin/create_activity", method = RequestMethod.POST)
    public String createActivity(@RequestParam Map<String, String> params) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date signUpStartTime = null;
        Date signUpEndTime = null;
        Date startTime = null;
        Date endTime = null;
        try {
            signUpStartTime = dateFormat.parse(params.get("signup_start_time"));
            signUpEndTime = dateFormat.parse(params.get("signup_end_time"));
            startTime = dateFormat.parse(params.get("start_time"));
            endTime = dateFormat.parse(params.get("end_time"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (signUpEndTime.before(signUpStartTime)) {
            return "redirect:/admin/warning/actvity_create_error";
        } else if (startTime.before(signUpEndTime)) {
            return "redirect:/admin/warning/actvity_create_error";
        } else if (endTime.before(startTime)) {
            return "redirect:/admin/warning/actvity_create_error";
        }
        boolean flag = activityService.createActivity(() -> {
            Activity activity = new Activity();
            try {
                //With
                activity.setTitle(params.get("title"));
                activity.setCaption(params.get("caption"));
                activity.setPosition(params.get("position"));
                activity.setLeaderId(Integer.parseInt(params.get("leader_id")));
                activity.setStartTime(dateFormat.parse(params.get("start_time")));
                activity.setEndTime(dateFormat.parse(params.get("end_time")));
                activity.setSignUpStartTime(dateFormat.parse(params.get("signup_start_time")));
                activity.setSignUpEndTime(dateFormat.parse(params.get("signup_end_time")));
                activity.setVolunteerMaxCount(Integer.parseInt(params.get("max_count")));
                activity.setVolunteerCount(0);
                //End With
            } catch (Exception e) {
                e.printStackTrace();
            }
            return activity;
        });
        if (flag) {
            return "redirect:/admin/message/actvity_create_success";
        } else {
            return "redirect:/admin/warning/actvity_create_failed";
        }
    }

    @GetMapping(value = "/admin/delete_activity/{id}")
    public String deleteActivity(@PathVariable(value = "id") String id) {
        boolean flag = activityService.deleteActivity(id);
        if (flag) {
            return "redirect:/admin/activities_list_page";
        } else {
            return "<script>alert('活动删除失败！请稍后重试或联系技术支持');</script>";
        }
    }

    @RequestMapping(path = "/admin/edit_activity", method = RequestMethod.POST)
    public String editActivity(@RequestParam Map<String, String> params) {
        boolean flag = activityService.editActivity(() -> {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Activity activity = new Activity();
            try {
                //With
                activity.setId(Integer.parseInt(params.get("id")));
                activity.setTitle(params.get("title"));
                activity.setCaption(params.get("caption"));
                activity.setPosition(params.get("position"));
                activity.setLeaderId(Integer.parseInt(params.get("leader_id")));
                activity.setStartTime(dateFormat.parse(params.get("start_time")));
                activity.setEndTime(dateFormat.parse(params.get("end_time")));
                activity.setSignUpStartTime(dateFormat.parse(params.get("signup_start_time")));
                activity.setSignUpEndTime(dateFormat.parse(params.get("signup_end_time")));
                activity.setVolunteerMaxCount(Integer.parseInt(params.get("max_count")));
                activity.setVolunteerCount(activityService.getActivity(params.get("id")).getVolunteerCount());
                //End With
            } catch (Exception e) {
                e.printStackTrace();
            }
            return activity;
        });
        if (flag) {
            return "redirect:/admin/activities_list_page";
        } else {
            return "<script>alert('活动修改失败！请稍后重试或联系技术支持');</script>";
        }
    }

    @RequestMapping(path = "/admin/search_activities", method = RequestMethod.POST)
    public ModelAndView searchActivitiesOfAdmin(@RequestParam Map<String, String> params, ModelAndView modelAndView) {
        modelAndView.setViewName("admin/activities_list");
        List<Activity> activitiesList = new ArrayList<>();
        List<String> leadersNameList = new ArrayList<>();
        @SuppressWarnings("unchecked")
        List<Leader> leaders = (List<Leader>)leaderService.getUsers(() -> {
            Leader leader = new Leader();
            leader.setUsername(params.get("leader"));
            return leader;
        });
        leaders.forEach(leader -> {
            activitiesList.addAll(
                activityService.getActivities(() -> {
                    Activity activity = new Activity();
                    activity.setTitle(params.get("title"));
                    activity.setCaption(params.get("caption"));
                    activity.setPosition(params.get("position"));
                    activity.setLeaderId(leader.getId());
                    return activity;
                })
            );
        });
        Iterator<Activity> iterator = activitiesList.iterator();
        while (iterator.hasNext()) {
            Activity activity = iterator.next();
            StatusTool.activityStatus(
                () -> activity,
                params.get("acti_status"),
                () -> iterator.remove(),
                () -> leadersNameList.add(
                        ((Leader)leaderService.getUser(activity.getLeaderId())).getUsername()
                    )
            );
        }    
        modelAndView.addObject("activitiesList", activitiesList);
        modelAndView.addObject("leadersNameList", leadersNameList);
        return modelAndView;
    }

    @RequestMapping(path = "/leader/search_activities", method = RequestMethod.POST)
    public ModelAndView searchActivitiesOfLeader(@RequestParam Map<String, String> params, ModelAndView modelAndView, HttpServletRequest request) {
        modelAndView.setViewName("leader/activities_list");
        List<Activity> activitiesList = activityService.getActivities(() -> {
            Activity activity = new Activity();
            activity.setTitle(params.get("title"));
            activity.setCaption(params.get("caption"));
            activity.setPosition(params.get("position"));
            activity.setLeaderId(
                Integer.parseInt(request.getSession().getAttribute("userid").toString())
            );
            return activity;
        });
        Iterator<Activity> iterator = activitiesList.iterator();
        while (iterator.hasNext()) {
            Activity activity = iterator.next();
            StatusTool.activityStatus(
                () -> activity,
                params.get("acti_status"),
                () -> iterator.remove(),
                () -> {}
            );
        }    
        modelAndView.addObject("activitiesList", activitiesList);
        return modelAndView;
    }

    @RequestMapping(path = "/volunteer/search_activities", method = RequestMethod.POST)
    public ModelAndView searchActivitiesOfVolunteer(@RequestParam Map<String, String> params, ModelAndView modelAndView, HttpServletRequest request) {
        modelAndView.setViewName("volunteer/activities_list");
        List<Activity> activitiesList = new ArrayList<>();
        List<String> leadersNameList = new ArrayList<>();
        List<String> notesCheckOutStatusList = new ArrayList<>();
        //List<String> notesStatusList = new ArrayList<>();
        List<Integer> notesIdList = new ArrayList<>();
        List<SignUpNote> signUpNotes = activitySignUpService.getNotes(() -> {
            SignUpNote temp = new SignUpNote();
            temp.setVolunteerId(
                Integer.parseInt((String)request.getSession().getAttribute("userid"))
            );
            return temp;
        });
        for (SignUpNote signUpNote : signUpNotes) {
            if (params.get("showCheckOutOnly") != null && params.get("showCheckOutOnly").equals("1")) {
                if (signUpNote.getCheckOutFlag() == 0) {
                    continue;
                }
            }
            Activity waitObj = activityService.getActivity(String.valueOf(signUpNote.getActivityId()));
            if (
                waitObj.getTitle().contains(params.get("title")) && 
                waitObj.getPosition().contains(params.get("position"))
            ) {
                activitiesList.add(waitObj);
                // leadersNameList.add(((Leader)leaderService.getUser(
                //     activityService.getActivity(
                //         String.valueOf(signUpNote.getActivityId())
                //     ).getLeaderId()
                // )).getUsername());
                notesIdList.add(signUpNote.getId());
                notesCheckOutStatusList.add(signUpNote.getCheckOutFlag() == 1 ? "已签到" : "未签到");
            }
        }
        Iterator<Activity> iterator = activitiesList.iterator();
        while (iterator.hasNext()) {
            Activity activity = iterator.next();
            StatusTool.activityStatus(
                () -> activity,
                params.get("acti_status"),
                () -> iterator.remove(),
                () -> leadersNameList.add(
                        ((Leader)leaderService.getUser(activity.getLeaderId())).getUsername()
                    )
            );
        }    
        modelAndView.addObject("activitiesList", activitiesList);
        modelAndView.addObject("leadersNameList", leadersNameList);
        modelAndView.addObject("notesCheckOutStatusList", notesCheckOutStatusList);
        modelAndView.addObject("notesIdList", notesIdList);
        return modelAndView;
    }

    @RequestMapping(path = "/volunteer/search_activities_grade", method = RequestMethod.POST)
    public ModelAndView searchActivitiesGradeOfVolunteer(@RequestParam("title") String title, ModelAndView modelAndView, HttpServletRequest request) {
        modelAndView.setViewName("volunteer/activities_grade_list");
        List<Activity> activitiesList = new ArrayList<>();
        List<String> notesCheckOutStatusList = new ArrayList<>();
        List<Integer> notesGradeList = new ArrayList<>();
        List<SignUpNote> signUpNotes = activitySignUpService.getNotes(() -> {
            SignUpNote temp = new SignUpNote();
            temp.setVolunteerId(
                Integer.parseInt((String)request.getSession().getAttribute("userid"))
            );
            return temp;
        });
        for (SignUpNote signUpNote : signUpNotes) {
            Activity waitObj = activityService.getActivity(String.valueOf(signUpNote.getActivityId()));
            if (waitObj.getTitle().contains(title)) {
                activitiesList.add(waitObj);
                notesCheckOutStatusList.add(signUpNote.getCheckOutFlag() == 1 ? "已签到" : "未签到");
                notesGradeList.add(signUpNote.getScore() == null ? -1 : signUpNote.getScore());
            }
        }
        modelAndView.addObject("activitiesList", activitiesList);
        modelAndView.addObject("notesCheckOutStatusList", notesCheckOutStatusList);
        modelAndView.addObject("notesGradeList", notesGradeList);
        return modelAndView;
    }
    
}
